<?php

namespace api\modules\v1\models;


use Yii;
use yii\web\NotFoundHttpException;

class ModuleJd
{
    protected static $client = null;
    protected static $app_key = '8b32b870a164fa1825891c3438b590c5';
    protected static $app_secret = 'f11ffc93a3b549d08fb761ba8b119b97';

    protected static $page_size = '20';

    /**
     * 订单查询
     * @param $request
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public static function order($request){
        $pageIndex = $request->get('pageIndex',1);
        $pageSize = $request->get('pageSize',self::$page_size);
        $type = $request->get('type',0);
        $time = $request->get('time',0);
        $childUnionId = $request->get('childUnionId',0);
        $key = $request->get('key','');

        $orderReq = [
            'pageNo'=>$pageIndex,
            'pageSize'=>$pageSize,
            'type'=>$type,
            'time'=>$time
        ];
        if($childUnionId) $orderReq['childUnionId'] = $childUnionId;
        if($key) $orderReq['key'] = $key;

        $param = array();
        $data['orderReq'] = $orderReq;
        $param['param_json'] = json_encode($data);
        $param_data = self::sign_method('jd.union.open.order.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $param_data);
        $result = json_decode($result,true);

        if($result['jd_union_open_order_query_response'] && $result['jd_union_open_order_query_response']['code'] == 0){
            $data_result = json_decode($result['jd_union_open_order_query_response']['result'],true);
            if($data_result && $data_result['code'] == 200){
                return $data_result['data'];
            }else{
                throw new NotFoundHttpException($data_result['message']);
            }
        }else return $result;
    }

    /**
     * 奖励订单查询接口
     * @param $request
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public static function orderBonus($request){
        $pageIndex = $request->get('pageIndex',1);
        $pageSize = $request->get('pageSize',self::$page_size);
        $optType = $request->get('optType',0);
        $startTime = $request->get('startTime','');
        $endTime = $request->get('endTime','');
        $sortValue = $request->get('sortValue','');

        $orderReq = [
            'pageNo'=>$pageIndex,
            'pageSize'=>$pageSize,
            'optType'=>$optType,
            'startTime'=>$startTime,
            'endTime'=>$endTime
        ];
        if($sortValue) $orderReq['sortValue'] = $sortValue;

        $param = array();
        $data['orderReq'] = $orderReq;
        $param['param_json'] = json_encode($data);
        $param_data = self::sign_method('jd.union.open.order.bonus.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $param_data);
        $result = json_decode($result,true);

        if($result['jd_union_open_order_query_response'] && $result['jd_union_open_order_query_response']['code'] == 0){
            $data_result = json_decode($result['jd_union_open_order_query_response']['result'],true);
            if($data_result && $data_result['code'] == 200){
                return $data_result['data'];
            }else{
                throw new NotFoundHttpException($data_result['message']);
            }
        }else return $result;
    }

    /**
     * 大字段商品查询接口
     * @param $request
     * @return bool
     * @throws NotFoundHttpException
     */
    public static function goodsBigfield($request){
        $skuIds = $request->get('skuIds',0);
        $fields = $request->get('fields',1);

        $goodsReq = ['skuIds'=>$skuIds];
        if($fields) $goodsReq['fields'] = $fields;

        $param = array();
        $data['goodsReq'] = $goodsReq;
        $param['param_json'] = json_encode($data);
        $GoodsList = self::sign_method('jd.union.open.goods.bigfield.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $GoodsList);
        $result = json_decode($result,true);

        if($result && $result['jd_union_open_goods_stuprice_query_response'] && $result['jd_union_open_goods_stuprice_query_response']['code'] == 0){
            $result_data = json_decode($result['jd_union_open_goods_stuprice_query_response']['result'],true);
            if($result_data && $result_data['code'] == 200){
                return $result_data['data'];
            }else {
                throw new NotFoundHttpException($result_data['message']);
            }
        }
        return false;
    }
    /**
     * 学生价商品查询接口
     * @param $request
     * @return bool
     * @throws NotFoundHttpException
     */
    public static function goodsStuprice($request){
        $skuIds = $request->get('skuIds',0);
        $pageIndex = $request->get('pageIndex',1);
        $pageSize = $request->get('pageSize',self::$page_size);
        $sortName = $request->get('sortName','');
        $sort = $request->get('sort','');
        $isBeginSecKill = $request->get('isBeginSecKill','');
        $secKillPriceFrom = $request->get('secKillPriceFrom','');
        $secKillPriceTo = $request->get('secKillPriceTo','');
        $cid1 = $request->get('cid1','');
        $cid2 = $request->get('cid2','');
        $cid3 = $request->get('cid3','');
        $owner = $request->get('owner','');
        $commissionShareFrom = $request->get('commissionShareFrom','');
        $commissionShareTo = $request->get('commissionShareTo','');

        $goodsReq = ['pageIndex'=>$pageIndex,'pageSize'=>$pageSize];
        if($sortName) $goodsReq['sortName'] = $sortName;
        if($sort) $goodsReq['sort'] = $sort;
        if($skuIds) $goodsReq['skuIds'] = $skuIds;
        if($isBeginSecKill) $goodsReq['isBeginSecKill'] = $isBeginSecKill;
        if($secKillPriceFrom) $goodsReq['secKillPriceFrom'] = $secKillPriceFrom;
        if($secKillPriceTo) $goodsReq['secKillPriceTo'] = $secKillPriceTo;
        if($cid1) $goodsReq['cid1'] = $cid1;
        if($cid2) $goodsReq['cid2'] = $cid2;
        if($cid3) $goodsReq['cid3'] = $cid3;
        if($owner) $goodsReq['owner'] = $owner;
        if($commissionShareFrom) $goodsReq['commissionShareFrom'] = $commissionShareFrom;
        if($commissionShareTo) $goodsReq['commissionShareTo'] = $commissionShareTo;

        $param = array();
        $data['goodsReq'] = $goodsReq;
        $param['param_json'] = json_encode($data);
        $GoodsList = self::sign_method('jd.union.open.goods.stuprice.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $GoodsList);
        $result = json_decode($result,true);

        if($result && $result['jd_union_open_goods_stuprice_query_response'] && $result['jd_union_open_goods_stuprice_query_response']['code'] == 0){
            $result_data = json_decode($result['jd_union_open_goods_stuprice_query_response']['result'],true);
            if($result_data && $result_data['code'] == 200){
                return $result_data['data'];
            }else {
                throw new NotFoundHttpException($result_data['message']);
            }
        }
        return false;
    }
    /**
     * 秒杀
     * @param $request
     * @return bool
     * @throws NotFoundHttpException
     */
    public static function goodsSeckill($request){
        $skuIds = $request->get('skuIds',0);
        $pageIndex = $request->get('pageIndex',1);
        $pageSize = $request->get('pageSize',self::$page_size);
        $sortName = $request->get('sortName','');
        $sort = $request->get('sort','');
        $isBeginSecKill = $request->get('isBeginSecKill','');
        $secKillPriceFrom = $request->get('secKillPriceFrom','');
        $secKillPriceTo = $request->get('secKillPriceTo','');
        $cid1 = $request->get('cid1','');
        $cid2 = $request->get('cid2','');
        $cid3 = $request->get('cid3','');
        $owner = $request->get('owner','');
        $commissionShareFrom = $request->get('commissionShareFrom','');
        $commissionShareTo = $request->get('commissionShareTo','');

        $goodsReq = ['pageIndex'=>$pageIndex,'pageSize'=>$pageSize];
        if($sortName) $goodsReq['sortName'] = $sortName;
        if($sort) $goodsReq['sort'] = $sort;
        if($skuIds) $goodsReq['skuIds'] = $skuIds;
        if($isBeginSecKill) $goodsReq['isBeginSecKill'] = $isBeginSecKill;
        if($secKillPriceFrom) $goodsReq['secKillPriceFrom'] = $secKillPriceFrom;
        if($secKillPriceTo) $goodsReq['secKillPriceTo'] = $secKillPriceTo;
        if($cid1) $goodsReq['cid1'] = $cid1;
        if($cid2) $goodsReq['cid2'] = $cid2;
        if($cid3) $goodsReq['cid3'] = $cid3;
        if($owner) $goodsReq['owner'] = $owner;
        if($commissionShareFrom) $goodsReq['commissionShareFrom'] = $commissionShareFrom;
        if($commissionShareTo) $goodsReq['commissionShareTo'] = $commissionShareTo;

        $param = array();
        $data['goodsReq'] = $goodsReq;
        $param['param_json'] = json_encode($data);
        $GoodsList = self::sign_method('jd.union.open.goods.seckill.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $GoodsList);
        $result = json_decode($result,true);
        if($result && $result['jd_union_open_goods_seckill_query_response'] && $result['jd_union_open_goods_seckill_query_response']['code'] == 0){
            $result_data = json_decode($result['jd_union_open_goods_seckill_query_response']['result'],true);
            if($result_data && $result_data['code'] == 200){
                return $result_data['data'];
            }else {
                throw new NotFoundHttpException($result_data['message']);
            }
        }
        return false;
    }
    /**
     * 所有分类
     * @param $request
     * @return bool|mixed|string
     */
    public static function categoryAll($request){
        $parentId = $request->get('parentId',0);
        $grade = $request->get('grade',0);
        $param = array();
        $data['req'] = [
            'parentId'   =>  $parentId,
            'grade' =>  $grade
        ];
        $param['param_json'] = json_encode($data);
        $param_data = self::sign_method('jd.union.open.category.goods.get',$param);
        $result = self::curl_post('https://router.jd.com/api', $param_data);
        $result = json_decode($result,true);
        if($result['jd_union_open_category_goods_get_response']){
            return json_decode($result['jd_union_open_category_goods_get_response']['result'],true);
        }
        return $result;
    }

    /**
     * 获取推广商品信息接口
     * @param $request
     * @return bool
     */
    public static function promotionGoodsInfo($get){
        $skuIds = $get['skuIds'];
        $param = array();
        $data['skuIds'] = $skuIds;//'5225346,7275691';
        $param['param_json'] = json_encode($data);
        $GoodsList = self::sign_method('jd.union.open.goods.promotiongoodsinfo.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $GoodsList);
        $result = json_decode($result,true);

        if($result && $result['jd_union_open_goods_promotiongoodsinfo_query_response'] && $result['jd_union_open_goods_promotiongoodsinfo_query_response']['code'] == 0){
            $result_data = json_decode($result['jd_union_open_goods_promotiongoodsinfo_query_response']['result'],true);
            if($result_data && $result_data['code'] == 200){
                return $result_data['data'];
            }
        }
        return false;
    }
    /**
     *关键词商品查询接口
     * @param $request
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public static function goodsSearch($request){
        {
            $cid1 = $request->get('cid1',0);
            $cid2 = $request->get('cid2',0);
            $cid3 = $request->get('cid3',0);
            $skuIds = $request->get('skuIds','');
            $keyword = $request->get('keyword','');
            $pricefrom = $request->get('pricefrom',0);
            $priceto = $request->get('priceto',0);
            $commissionShareStart = $request->get('commissionShareStart',0);
            $commissionShareEnd = $request->get('commissionShareEnd',0);
            $owner = $request->get('owner',0);
            $isCoupon = $request->get('isCoupon',0);
            $isPG = $request->get('isPG',0);
            $pingouPriceStart = $request->get('pingouPriceStart',0);
            $pingouPriceEnd = $request->get('pingouPriceEnd',0);
            $isHot = $request->get('isHot',0);
            $brandCode = $request->get('brandCode',0);
            $shopId = $request->get('shopId',0);
            $hasContent = $request->get('hasContent',0);
            $hasBestCoupon = $request->get('hasBestCoupon',0);
            $pageIndex = $request->get('pageIndex',1);
            $pageSize = $request->get('pageSize',self::$page_size);
            $sortName = $request->get('sortName','');
            $sort = $request->get('sort','');

            $goodsReqDTO = [];
            $goodsReqDTO['pageIndex'] = $pageIndex;
            $goodsReqDTO['pageSize'] = $pageSize;
            if($sortName) $goodsReqDTO['sortName'] = $sortName;
            if($sort) $goodsReqDTO['sort'] = $sort;
            if($cid1) $goodsReqDTO['cid1'] = $cid1;
            if($cid2) $goodsReqDTO['cid2'] = $cid2;
            if($cid3) $goodsReqDTO['cid3'] = $cid3;
            if($skuIds) $goodsReqDTO['skuIds'] = $skuIds;
            if($keyword) $goodsReqDTO['keyword'] = $keyword;
            if($pricefrom) $goodsReqDTO['pricefrom'] = $pricefrom;
            if($priceto) $goodsReqDTO['priceto'] = $priceto;
            if($commissionShareStart) $goodsReqDTO['commissionShareStart'] = $commissionShareStart;
            if($commissionShareEnd) $goodsReqDTO['commissionShareEnd'] = $commissionShareEnd;
            if($owner) $goodsReqDTO['owner'] = $owner;
            if($isCoupon) $goodsReqDTO['isCoupon'] = $isCoupon;
            if($pingouPriceStart) $goodsReqDTO['pingouPriceStart'] = $pingouPriceStart;
            if($isPG) $goodsReqDTO['isPG'] = $isPG;
            if($pingouPriceEnd) $goodsReqDTO['pingouPriceEnd'] = $pingouPriceEnd;
            if($isHot) $goodsReqDTO['isHot'] = $isHot;
            if($brandCode) $goodsReqDTO['brandCode'] = $brandCode;
            if($shopId) $goodsReqDTO['shopId'] = $shopId;
            if($hasContent) $goodsReqDTO['hasContent'] = $hasContent;
            if($hasBestCoupon) $goodsReqDTO['hasBestCoupon'] = $hasBestCoupon;
        }
        $param = array();
        $data['goodsReqDTO'] = $goodsReqDTO;
        $param['param_json'] = json_encode($data);
        $param_data = self::sign_method('jd.union.open.goods.query',$param);
        $result = self::curl_post('https://router.jd.com/api', $param_data);
        $result = json_decode($result,true);

        if($result && $result['jd_union_open_goods_query_response'] && $result['jd_union_open_goods_query_response']['result']){
            $result_data = json_decode($result['jd_union_open_goods_query_response']['result'],true);
            if($result_data['code'] == 200){
                return $result_data['data'];
            }else {
                throw new NotFoundHttpException($result_data['message']);
            }
        }
        return $result;
    }
    /**
     * 商品详情
     * @param $request
     * @return mixed
     */
    public static function goodsInfo($request){
        $id = $request->get('id','');
        $data = self::getJDCache('jd-goods',[$id]);
        if(!$data){
            $param = array();
            $data['skuIds'] = $id;//'5225346,7275691';
            $param['param_json'] = json_encode($data);
            $GoodsList = self::sign_method('jd.union.open.goods.promotiongoodsinfo.query',$param);
            $result = self::curl_post('https://router.jd.com/api', $GoodsList);
            $result = json_decode($result,true);
            if($result && $result['jd_union_open_goods_promotiongoodsinfo_query_response'] && $result['jd_union_open_goods_promotiongoodsinfo_query_response']['code'] == 0){
                $result_data = json_decode($result['jd_union_open_goods_promotiongoodsinfo_query_response']['result'],true);
                if($result_data && $result_data['code'] == 200){
                    return $result_data['data'][0];
                }
            }
        }
        return $data;
    }
    /**
     * 京粉精选商品查询接口
     * @param $request
     * @return mixed
     */
    public static function goodsJingfen($request){
        $jd_key = 'jd.union.open.goods.jingfen.query';
        $jd_data = self::getJDCache($jd_key, $request->get());
        if(!$jd_data){
            $eliteId = $request->get('eliteId',0);
            $pageIndex = $request->get('pageIndex',1);
            $pageSize = $request->get('pageSize',self::$page_size);
            $sortName = $request->get('sortName','');
            $sort = $request->get('sort','');

            $goodsReq = [
                'eliteId'   =>  intval($eliteId),
                'pageIndex' =>  intval($pageIndex),
                'pageSize'  =>  intval($pageSize)
            ];
            if($sortName) $goodsReq['sortName'] = $sortName;
            if($sort) $goodsReq['sort'] = $sort;

            $param = array();
            $data['goodsReq'] = $goodsReq;
            $param['param_json'] = json_encode($data);
            $param_data = self::sign_method($jd_key,$param);
            $result = self::curl_post('https://router.jd.com/api', $param_data);
            $result = json_decode($result,true);
            if($result['jd_union_open_goods_jingfen_query_response'] && $result['jd_union_open_goods_jingfen_query_response']['code'] == 0){
                $data_result = json_decode($result['jd_union_open_goods_jingfen_query_response']['result'],true);
                if($data_result && $data_result['code'] == 200){
                    $jd_data = $data_result['data'];
                    //TODO:保存缓存
                    self::setJDCache($jd_key, $request->get(), $jd_data);
                    foreach ($jd_data as $k=>$v){
                        self::setJDCache('jd-goods', [$v['skuId']], $v);
                    }
                }
            }
        }
        return $jd_data;
    }

    /**
     * 获取通用推广链接
     * @param $request
     * @return array
     */
    public static function promotionCommon($request, $member_id){
        $id = $request->post('id','');
        $materialId = $request->post('materialId','');
        $couponUrl = $request->get('couponUrl','');

        $goods = self::getJDCache('jd-goods',[$id]);
        if($goods && is_array($goods)){
            $materialId = $goods['materialUrl'];
            $couponUrl = $goods['couponInfo']['couponList'][0]['link'];
//        if($member_id>0) $promotionCodeReq['ext1']  =   $member_id;
        }
        $promotionCodeReq = [
            'materialId'=>$materialId,
            'siteId'=>'1945051184',
            'positionId'=>'1952895851'
        ];
        if($couponUrl)  $promotionCodeReq['couponUrl']  =   $couponUrl;

        $param = array();
        $data['promotionCodeReq'] = $promotionCodeReq;
        $param['param_json'] = json_encode($data);
        $param_data = self::sign_method('jd.union.open.promotion.common.get',$param);
        $result = self::curl_post('https://router.jd.com/api', $param_data);
        $result = json_decode($result,true);

        $jd_data = [];
        if($result['jd_union_open_promotion_common_get_response'] && $result['jd_union_open_promotion_common_get_response']['code'] == 0){
            $data_result = json_decode($result['jd_union_open_promotion_common_get_response']['result'],true);
            if($data_result && $data_result['code'] == 200){
                $jd_data = $data_result['data'];
            }
        }
        return $jd_data;
    }

    /**
     * 获取京东数据缓存
     * @param $key
     * @param $params
     * @return mixed
     */
    protected static function getJDCache($key, $params){
        $cache = Yii::$app->cache;
        unset($params['access-token']);
        $redis_key = $key . '-' . implode('-',$params);
        return $cache->get($redis_key);
    }

    /**
     * 保存京东数据缓存
     * @param $key
     * @param $params
     * @param $data
     * @param int $expire
     */
    protected static function setJDCache($key, $params, $data, $expire = 86400){
        $cache = Yii::$app->cache;
        unset($params['access-token']);
        $redis_key = $key . '-' . implode('-',$params);
        return $cache->set($redis_key, $data, $expire);
    }


    // post请求
    protected static function curl_post($url, $curlPost)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    protected static function sign_method($method,$data=array()){
        date_default_timezone_set("PRC");
        $sign_method = array(
            'app_key'=> self::$app_key,
            'timestamp'=> date('Y-m-d H:i:s'),
            'format' => 'json',
            'method' => $method,
            'v' => '1.0',
            'sign_method'=>'md5',
        );
        $sign_method = array_merge($sign_method,$data);
        ksort($sign_method);
        // var_dump($array_merge);die();
        $data = self::$app_secret;
        foreach ($sign_method as $key => $value) {
            $data .= trim($key) .trim($value);
        }
        $data .= self::$app_secret;
        $sign_method['sign'] = strtoupper(md5($data));
        // echo "<pre>";
        // var_dump($sign_method);die();
        return $sign_method;
    }
}